import React from "react";

import PageContent from '../../PageContent'

import { ajax ,batchAjax,showResultMessage,isNull,inArray} from '../../common';

import {Row,Col,Divider,message } from 'antd';

import {UIDataTableView} from '../../uicomponents/UIDataComponentView';

import UIFormView from '../../uicomponents/UIFormView';

import UIForm from '../../uicomponents/UIForm';

import UIView from "../../uicomponents/UIView";

/**路由设置 */
const pageContentMap = {
	'/': {
        text: '模型服务模板列表',
        icon: '',
        getComponent: (owner, props) => {
            return (<ProductModelServiceTemplateListPanel {...props} key="serviceTemplateListPanel" />);
        }
	},
    '/editModelServiceTemplate': {
        text: '编辑服务模板',
        icon: 'edit',
        getComponent: (owner, props) => {
            return (<ProductModelServiceTemplateEditPanel {...props} key="serviceTemplateEditPanel" />);
        }
	},
}
/** 
 * 产品模型代码模板管理应用
*/
export default class ProductModelServiceCodeTemplateManageApp extends React.Component {

	render() {
		return (
			<PageContent {...this.props} pageInstance={this} contentMap={pageContentMap} >
				
			</PageContent>
		);
	}
}

/**
 * 服务模板列表
 */
class ProductModelServiceTemplateListPanel extends React.Component {

	state = {
		formTitle : '',
	}

	actionHandler = (actionEvent) => {

		const {serviceTemplateListRef,serviceTemplateFormRef,selectServiceTemplateIds} = this;

		return {
			refresh : () => {
				serviceTemplateListRef.loadData();
			},
			addNewModelServiceTemplate : () => {
				this.setState({formTitle : '新增服务模板'});
				serviceTemplateFormRef.openModal();
			},
			editModelServiceTemplate : () => {
				ajax('PRODUCT/MODEL/productModelObject/getModelServiceTemplateById',{id : actionEvent.params.id},(data) => {
					this.setState({formTitle : '编辑服务模板'});
					serviceTemplateFormRef.openModal(() => {
						serviceTemplateFormRef.setFormData(data);
					});
				});
			},
			doSave : () => {
				serviceTemplateFormRef.getFormData((formData) => {
					ajax('PRODUCT/MODEL/productModelObject/saveModelServiceTemplate',formData,() => {
						serviceTemplateFormRef.closeModal();
						serviceTemplateListRef.loadData();
					});
				});
			},
			deleteModelServiceTemplates : () => {
				const selectIds = isNull(actionEvent.params) ? selectServiceTemplateIds : [actionEvent.params.id];
				ajax('PRODUCT/MODEL/productModelObject/deleteModelServiceTemplate',{ids : selectIds},() => {
					serviceTemplateListRef.loadData();
				});

			}
		};
	}

    render() {
		const tableProps = {
            actionHandler: this.actionHandler,
            searchFormId : 'productModelServiceTemplateQueryForm',
			actionGroupId: 'modelServiceTemplateListActionGroup',
			rowActionGroupId: 'modelServiceTemplateRowActionGroup',
			tableConfigId: 'productModelServiceTemplateTable',
			dataUrl: 'PRODUCT/MODEL/productModelObject/queryModelServiceTemplateList',
			selectMode: 'multi',
			autoLoad: true,
			ref: (inst) => { this.serviceTemplateListRef = inst },
			onSelectChange:
				(selectRowKeys) => {
					this.selectServiceTemplateIds = selectRowKeys;
				}
			,
			setToolbarState: (toolBar, selectRowKeys) => {
				if (selectRowKeys.length > 0) {
					toolBar.enable('delete');
				}
				else {
					toolBar.disable('delete');
				}
			}
		};
		
		const formProps = {
            width : 800,
			ref: (inst) => { this.serviceTemplateFormRef = inst },
			formConfigId: 'productModelServiceTemplateForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		}

        return (
            <React.Fragment>
				<UIDataTableView {...this.props} {...tableProps} />
				<UIFormView {...formProps} />
			</React.Fragment>
        );
    }
}

/**
 * 编辑服务模板
 */
class ProductModelServiceTemplateEditPanel extends React.Component {

	state = {
		formTitle : '',
		serviceTemplateItem : null,
	}

	componentDidMount(){
		this.serviceTemplate = this.props.location.state;
		this.serviceTemplateItemListRef.loadData({serviceTemplateId:this.serviceTemplate.id});
	}

	actionHandler = (avtionEvent) => {
		const {serviceTemplate,serviceTemplateItemListRef,serviceTemplateItemFormRef,
			selectServiceTemplateItemIds,serviceTemplateItemParameterRef,
			serviceTemplateItemParameterViewRef} = this;

		return {
			refresh : () => {
				serviceTemplateItemListRef.loadData({serviceTemplateId:serviceTemplate.id});
			},
			addNewModelServiceTemplateItem : () => {
				this.setState({formTitle : '新增服务模板项'});
				serviceTemplateItemFormRef.openModal();
			},
			editModelServiceTemplateItem : () => {
				this.setState({formTitle : '编辑服务模板项'});
				serviceTemplateItemFormRef.openModal(() => {
					serviceTemplateItemFormRef.setFormData(avtionEvent.params);
				});
			},
			doSave : () => {
				serviceTemplateItemFormRef.getFormData(formData => {
					formData.serviceTemplateId = serviceTemplate.id;
					ajax('PRODUCT/MODEL/productModelObject/saveModelServiceTemplateItem',formData,() => {
						serviceTemplateItemFormRef.closeModal();
						serviceTemplateItemListRef.loadData({serviceTemplateId:serviceTemplate.id});
					});
				})
			},
			deleteModelServiceTemplateItems : () => {
				const selectIds = isNull(avtionEvent.params) ?  selectServiceTemplateItemIds : [avtionEvent.params.id];

				ajax('PRODUCT/MODEL/productModelObject/deleteModelServiceTemplateItem',{ids : selectIds},() => {
					serviceTemplateItemListRef.loadData({serviceTemplateId:serviceTemplate.id});
				});
			},
			editModelServiceTemplateItemParameter : () => {
				this.setState({serviceTemplateItem : avtionEvent.params });
				setTimeout(() => {
					serviceTemplateItemParameterViewRef.openModal();
				});
			}
		};
    }
    
    serviceTemplateItemParameterActionHandler = (actionEvent) => {
        return {
            doSave : () => {
                this.serviceTemplateItemParameterRef.saveModelServiceTemplateItemParams();
            }
        }
    }

	render() {
		const tableProps = {
            actionHandler: this.actionHandler,
            searchFormId : 'productModelServiceTemplateItemQueryForm',
			actionGroupId: 'modelServiceTemplateItemListActionGroup',
			rowActionGroupId: 'modelServiceTemplateItemRowActionGroup',
			tableConfigId: 'productModelServiceTemplateItemTable',
			dataUrl: 'PRODUCT/MODEL/productModelObject/queryModelServiceTemplateItemList',
			selectMode: 'multi',
			autoLoad: false,
			ref: (inst) => { this.serviceTemplateItemListRef = inst },
			onSelectChange:
				(selectRowKeys) => {
					this.selectServiceTemplateItemIds = selectRowKeys;
				}
			,
			setToolbarState: (toolBar, selectRowKeys) => {
				if (selectRowKeys.length > 0) {
					toolBar.enable('delete');
				}
				else {
					toolBar.disable('delete');
				}
			}
		};
		
		const formProps = {
            width : 800,
			ref: (inst) => { this.serviceTemplateItemFormRef = inst },
			formConfigId: 'productModelServiceTemplateItemForm',
			actionGroupId: 'saveActionGroup',
			actionHandler: this.actionHandler,
			inPop: true,
			destroyOnClose: true,
			title: this.state.formTitle,
		}

        return (
            <React.Fragment>
				<UIDataTableView {...this.props} {...tableProps} />
				<UIFormView {...formProps} />
				<UIView actionGroupId="saveActionGroup" actionHandler={this.serviceTemplateItemParameterActionHandler} width={900} ref={(inst) => { this.serviceTemplateItemParameterViewRef = inst }} inPop={true} title="服务模板参数配置" destroyOnClose={true}>
					<ProductServiceTemplateItemParameterPanel ref={(inst) => { this.serviceTemplateItemParameterRef = inst }} serviceTemplateItem={this.state.serviceTemplateItem}/>
				</UIView>
				
			</React.Fragment>
        );
	}
}

/**
 * 服务模板参数列表
 */
class ProductServiceTemplateItemParameterPanel extends React.Component {

    state = {
        chooseDataTypeActionHandler : null,
	}
	
	componentDidMount(){
		const {serviceTemplateItem} = this.props;
		//console.log(serviceTemplateItem);
		if(isNull(serviceTemplateItem) === false){
			this.setModelServiceTemplateItem(serviceTemplateItem);
		}
	}

    setModelServiceTemplateItem = (serviceTemplateItem) => {
		this.serviceTemplateItem = serviceTemplateItem;

		const {outputParamFormRef,inputParamListRef} = this;
		
        ajax('PRODUCT/MODEL/productModelObject/getModelServiceTemplateItemParameters',{id:serviceTemplateItem.id},(data) => {
			//console.log(data);
			const inputParams = [];
			data.map(param => {
				if(param.parameterType === 'OUTPUT'){
					outputParamFormRef.setFormData(param);
				}
				else if(param.parameterType === 'INPUT'){
					inputParams.push(param);
				}
			});
			inputParamListRef.setListData(inputParams);
        });
    }

    saveModelServiceTemplateItemParams = () => {

        const {serviceTemplateItem,outputParamFormRef,inputParamListRef} = this;
        const params = [];

        outputParamFormRef.getFormData((data) => {
            data.serviceTemplateItemId = serviceTemplateItem.id;
            data.parameterType = 'OUTPUT';
            params.push(data);
        });

        const dataList = inputParamListRef.getListData();

        dataList.map((param,index) => {
            param.serviceTemplateItemId = serviceTemplateItem.id;
            if(param.id < 0){
                param.id = 0;
            }
            param.parameterType = 'INPUT';
            param.sortIndex = index + 1;
            params.push(param);
        });

        ajax('PRODUCT/MODEL/productModelObject/setModelServiceTemplateItemParameter/' + serviceTemplateItem.id,params,(data) => {
            //console.log(data);
            message.success('保存完成');
        },'application/json');

    }

    inputParamListActionHandler = (actionEvent) => {
       
        const {serviceTemplateItem,inputParamFormRef,selectInputParamIds} = this;
        return {
            addNewInputParameter : () => {
                inputParamFormRef.openModal();
            },
            closeInputParamDialog : () => {

                inputParamFormRef.closeModal();
            },
            doSave : () => {
                
                const dataList = this.inputParamListRef.getListData();

                inputParamFormRef.getFormData((data) => {
                    data.serviceTemplateItemId = serviceTemplateItem.id;
                    data.parameterType = 'INPUT';
                    data.id = 0 - (dataList.length + 1);
                    if(data.sortIndex === undefined){
                        data.sortIndex = dataList.length;
                    }

                    dataList.push(data);
                    
                    this.inputParamListRef.setListData(dataList);

                    inputParamFormRef.closeModal();

                });
            },
            editInputParameter : () => {
                const inputParam = actionEvent.params;
                inputParamFormRef.openModal(() => {
                    inputParamFormRef.setFormData(inputParam);
                })
            },
            deleteInputParameter : () => {
                const selectIds = isNull(actionEvent.params) ? selectInputParamIds : [actionEvent.params.id];

                const newInputList = [];

                const dataList = this.inputParamListRef.getListData();

                dataList.map((input) => {
                    
                    if(inArray(input.id,selectIds) === -1){
                        newInputList.push(input);
                    }
                });

                this.inputParamListRef.setListData(newInputList);
                
            },
            moveUp : () => {
                const inputParam = actionEvent.params;
                const dataList = this.inputParamListRef.getListData();
                const dataIds = [];
                if(inputParam.sortIndex > 0){
                    
                    for(let i=0;i< dataList.length;i++ ){
                        dataIds.push(dataList[i].id);
                    }

                    const index = inArray(inputParam.id,dataIds);

                    if(index !== -1){
                        inputParam.sortIndex = inputParam.sortIndex - 1;
                        dataList[index - 1].sortIndex = dataList[index - 1].sortIndex + 1;
                        dataList[index] = dataList[index - 1];
                        dataList[index - 1] = inputParam;
                    }

                    this.inputParamListRef.setListData(dataList);
                }
            },
            moveDown : () => {
                const inputParam = actionEvent.params;
                const dataList = this.inputParamListRef.getListData();
                const dataIds = [];
                if(inputParam.sortIndex < dataList.length){
                    
                    for(let i=0;i< dataList.length;i++ ){
                        dataIds.push(dataList[i].id);
                    }

                    const index = inArray(inputParam.id,dataIds);

                    if(index !== -1){
                        inputParam.sortIndex = inputParam.sortIndex + 1;
                        dataList[index + 1].sortIndex = dataList[index + 1].sortIndex - 1;
                        dataList[index] = dataList[index + 1];
                        dataList[index + 1] = inputParam;
                    }

                    this.inputParamListRef.setListData(dataList);
                }
            }
        }
    }

    render() {

        const tableProps = {
            bordered : false,
            ref: (inst) => { this.inputParamListRef = inst },
            tableConfigId: 'productModelServiceParameterTemplateTable',
            actionGroupId: 'inputParameterActionGroup',
            rowActionGroupId : 'inputParameterRowActionGroup',
            actionHandler: this.inputParamListActionHandler,
            autoLoad: false,
            selectMode: 'multi',
            setToolbarState: (topToolBar, selectedIds) => {
                if (selectedIds.length > 0) {
                    topToolBar.enable('delete');
				    topToolBar.enable('edit');
                }
                else {
                    topToolBar.disable('delete');
                    topToolBar.disable('edit');
                }
            },
            onSelectChange:
                (selectRowKeys) => {
                    this.selectInputParamIds = selectRowKeys;
                }
            ,
        };

        return (
            <React.Fragment>
                <Row style={{marginTop : '0px'}}>
                    <Col span={24}>
                        <Divider orientation="left">输出参数</Divider>
                        <UIForm wrappedComponentRef={(inst) => this.outputParamFormRef = inst} formConfigId="productServiceOutputParameterTemplateForm"/>
                    </Col>
                </Row>
                <Row style={{marginTop : '0px'}}>
                    <Col span={24}>
                        <Divider orientation="left">输入参数</Divider>
                        <UIDataTableView {...tableProps} />
                    </Col>
                </Row>
                <UIFormView 
                    zIndex={2000}
                    title="输入参数"
                    inPop={true}
                    destroyOnClose={true}
                    formConfigId="productServiceInputParameterTemplateForm"
                    ref={ (inst) => { this.inputParamFormRef = inst } }
                    actionGroupId="inputParameterTemplateFormActionGroup"
                    actionHandler={this.inputParamListActionHandler}
                />
            </React.Fragment>
        );
    }
}
